<?php
class system_file_io {
	
	public static function mkdir($dir) {
		if(!is_dir($dir)) {
			self::mkdir(dirname($dir));
			@mkdir($dir, 0777);
		}
	}
	
	public static function rmdir($dir) {
		foreach(self::dir($dir) as $v) {
			if(is_dir($dir . '/' . $v)) {
				self::rmdir($dir . '/' . $v);
			} else {
				@unlink($dir . '/' . $v);
			}
		}
		@rmdir($dir);
	}
	
	public static function dir($dir) {
		if(!is_dir($dir)) {
			throw new Exception($dir . ' is not folder.');
		}
		$d = dir($dir);
		$list = array();
		while(false !== ($entry = $d->read())) {
			if($entry == '.' or $entry == '..') continue;
			$list[] = $entry;
		}
		$d->close();
		return $list;
	}
	
	static public function md5Filename($file = null, $content = null) {
		if($file && !$content) {
			$md5_code = md5_file($file);
		} else {
			$md5_code = md5($content);
		}
		return md5($md5_code);
	}
	
	public static function getFileType($file) {
		$type = '';
		if(!!($pos = strripos($file, '.'))) {
			$type = strtolower(substr($file, $pos));
		}
		return $type;
	}
	
	
	public static function writeFile($file, $string, $umask = 0755) {
		$dir = dirname($file);
		if(!is_dir($dir)) {
			self::mkdir($dir);
		}
		$result = false;
		$f = @fopen($file, 'ab+');
		if($f) {
			fseek($f, 0);
			ftruncate($f, 0);
			$tmp = @fwrite($f, $string);
			if(!($tmp === FALSE)) {
				$result = true;
			}
			@fclose($f);
		}
		@chmod($file, $umask);
		return $result;
	}
	
	public static function readFile($file, $flock = true) {
		$result = false;
		if(!is_file($file)) {
			return false;
		}
		$f = @fopen($file, 'rb');
		if($f) {
			if($flock) @flock($f, LOCK_SH);
			$result = stream_get_contents($f);
			if($flock) @flock($f, LOCK_UN);
			@fclose($f);
		}
		return $result;
	}
}